package com.epam.training.concurrency.first.task4;

import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.epam.training.concurrency.first.task3.CircularBuffer;

/**
 * 
 * @author Bogdan
 *
 */
public class OrderThread extends Thread {

	private static class Lock {
	}

	public static final int FIRST_NUMBER = 1;
	public static final int MAX_SLEEP = 1000;
	private static int lastNumber = FIRST_NUMBER;
	private static int order = FIRST_NUMBER;
	private int number;

	private final static Lock LOCK = new Lock();

	public OrderThread() {
		number = OrderThread.lastNumber++;
	}

	@Override
	public void run() {

		while (true) {

			synchronized (LOCK) {

				while (number != order) {
					try {
						LOCK.wait();
					} catch (InterruptedException e) {
						Logger.getLogger(CircularBuffer.class.getName()).log(
								Level.SEVERE, null, e);
					}
				}

				System.out.format("Thread number: %d\n", number);
				checkOrder();

				try {
					Random random = new Random();
					sleep(random.nextInt(MAX_SLEEP));
				} catch (InterruptedException e) {
					Logger.getLogger(CircularBuffer.class.getName()).log(
							Level.SEVERE, null, e);
				}

				LOCK.notifyAll();
			}
		}
	}

	private void checkOrder() {
		order++;

		if (order == lastNumber) {
			order = FIRST_NUMBER;
			System.out.println("Finished\n");
		}
	}
}
